<template>
  <el-dialog
    title="添加菜品"
    class="addDishList"
    v-model="props.dialogVisible"
    width="60%"
    :before-close="dialogHandle"
  >
    <el-input
      v-model="seachValue"
      class="seachDish"
      placeholder="请输入菜品名称进行搜索"
      :prefix-icon="Search"
      style="width: 293px; height: 40px"
      size="small"
      clearable
    >
    </el-input>
    <div class="addDish">
      <div class="leftCont">
        <div class="tab" v-show="seachValue == ''">
          <span
            v-for="(item, index) in categoryList"
            :key="index"
            :class="{ active: index === keyIndex }"
            @click="checkHandle(index, item.id!)"
            >{{ item.name }}</span
          >
        </div>
        <div class="dishList">
          <div class="table">
            <div v-if="dishList.length === 0">
              <Empty :isSearch="isSearch" />
            </div>
            <el-checkbox-group v-if="dishList.length > 0" v-model="checkedList" @change="checkedListHandle">
              <div v-for="item in dishList" :key="item.id" class="items">
                <el-checkbox :value="item.name">
                  <div class="item">
                    <span style="flex: 3; text-align: left">{{ item.name }}</span>
                    <span>{{ item.status == 0 ? '停售' : '在售' }}</span>
                    <span>{{ decimalsReplenish(item.price) }}</span>
                  </div>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <div class="rightCont">
        <div class="title">已选菜品({{ checkedListAll.length }})</div>
        <div class="items">
          <div v-for="item in checkedListAll" :key="item.id" class="item">
            <span>{{ item.name }}</span>
            <span class="price">￥ {{ decimalsReplenish(item.price) }} </span>
            <span class="del" @click="delCheck(item.id)"> </span>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogHandle">取消</el-button>
        <el-button type="primary" @click="addDishHandle">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { CATEGORY_TYPE } from '@/constants'
import Empty from '@/components/Empty/index.vue'
import { Search } from '@element-plus/icons-vue'
import { decimalsReplenish } from '@/utils/index'
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  setmeal_dishes: {
    type: Array,
    default: [],
  },
})
const emit = defineEmits(['getCheckList', 'dialogHandle'])
// 是否搜索
const isSearch = ref(false)
const seachValue = ref('')
// 左侧选择的菜品列表
const checkedList = ref<DishListResult[]>([])
// 所有已选择的菜品列表
const checkedListAll = ref<DishListResult[]>([])
// 当前选中菜品分类下标
const keyIndex = ref(0)
// 当前分类的菜品列表
const dishList = ref<DishListResult[]>([])
// 所有分类的菜品列表
const allDishList = ref<DishListResult[]>([])

import useCategory from '@/hooks/useCategory'
import { getDishListAPI } from '@/api/business/dish'
import { DishListResult } from '@/types/dish'
const { categoryList, getCategorysByType } = useCategory()
onMounted(async () => {
  await getCategorysByType(CATEGORY_TYPE.dish)
  if (categoryList.value) {
    const id = categoryList.value[0].id
    getDishList(id!)
  }
  // 已选择的菜品
  if (props.setmeal_dishes.length > 0) {
    checkedList.value = props.setmeal_dishes.map((item: any) => item)
    checkedListAll.value = checkedList.value.reverse()
  }
})
const checkHandle = async (index: number, id: number) => {
  keyIndex.value = index
  getDishList(id)
}
// 根据分类获取菜品列表
const getDishList = async (id: number) => {
  let { data } = await getDishListAPI(id)
  dishList.value = data

  const isDishInList = (list: DishListResult[], dish: DishListResult) => {
    return list.some(existingDish => existingDish.id === dish.id)
  }
  // 将新数据添加到所有菜品列表中，同时去重
  data.forEach(newDish => {
    if (!isDishInList(allDishList.value, newDish)) {
      allDishList.value.push(newDish)
    }
  })
}
// 关键词收搜菜品列表分类
// const getDishByName = async (name: string) => {
//   let params = {
//     page: 1,
//     pageSize: 10,
//     name: name,
//   };
//   let { data } = await getDishPageAPI(params);

// };
// 选择列表菜品
const checkedListHandle = (value: string[]) => {
  // 选中菜品
  const selectedDishes = allDishList.value.filter(item => value.includes(item.name))
  const dishListCat = [...checkedListAll.value, ...selectedDishes]

  // 使用 Map 来确保菜品对象的唯一性（基于名称），同时保留菜品对象
  const uniqueDishesMap = new Map(dishListCat.map(dish => [dish.name, dish]))
  // 将 Map 的值（即唯一的菜品对象）转换为一个数组
  const newDishesToAdd: DishListResult[] = [...uniqueDishesMap.values()]

  checkedListAll.value = [...newDishesToAdd]
}
// 已选列表删除菜品
const delCheck = (id: number) => {
  const index = checkedList.value.findIndex(item => item.id === id)
  const indexAll = checkedListAll.value.findIndex(item => item.id === id)
  checkedList.value.splice(index, 1)
  checkedListAll.value.splice(indexAll, 1)
}
const addDishHandle = () => {
  emit('getCheckList', checkedListAll.value)
  dialogHandle()
}
// 关闭弹窗
const dialogHandle = () => [emit('dialogHandle', false)]
</script>
<style scoped lang="scss">
.addDishList {
  .seachDish {
    position: absolute;
    top: 12px;
    right: 20px;
  }

  .el-dialog__footer {
    padding-top: 27px;
  }

  .el-dialog__body {
    padding: 0;
    border-bottom: solid 1px #efefef;
  }
  .seachDish {
    .el-input__inner {
      height: 40px;
      line-height: 40px;
    }
  }
}
.addDish {
  width: 100%;
  display: flex;
  line-height: 40px;
  .leftCont {
    display: flex;
    border-right: solid 1px #efefef;
    width: 60%;
    padding: 15px;
    .tab {
      display: flex;
      flex-direction: column;
      width: 110px;
      border-right: solid 2px #f4f4f4;
      span {
        display: block;
        text-align: center;
        cursor: pointer;
        position: relative;
      }
    }
    .active {
      font-weight: bold;
    }
    .active::after {
      content: '';
      display: inline-block;
      background: #000;
      width: 2px;
      height: 40px;
      position: absolute;
      right: -2px;
    }
    .dishList {
      flex: 1;
      height: 400px;
      overflow-y: scroll;
      padding: 10px 20px;

      .table {
        .items {
          padding: 0 10px;
          display: flex;
          .item {
            display: flex;
            padding-right: 20px;
            span {
              display: inline-block;
              text-align: center;
              flex: 1;
              font-weight: normal;
            }
          }
        }
      }
    }
  }
  .rightCont {
    width: 40%;
    .title {
      font-weight: 700;
      padding: 15px;
    }
    .items {
      height: 338px;
      padding: 4px 15px;
      overflow: scroll;
      .item {
        box-shadow: 0px 1px 4px 3px rgba(0, 0, 0, 0.03);
        display: flex;
        align-items: center;
        // justify-content: space-between;
        padding: 0 10px;
        margin-bottom: 20px;
        border-radius: 6px;
        color: #818693;
        span:first-child {
          text-align: left;
          color: #20232a;
          flex: 1;
        }
        .price {
          display: inline-block;
          flex: 1;
          text-align: left;
        }
        .del {
          width: 20px;
          height: 20px;
          background: url('./../../../assets/icons/btn_clean@2x.png') center;
          background-size: cover;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
